package com.yocard.yxyd.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.gyf.barlibrary.ImmersionBar;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yocard.yxyd.R;
import com.yocard.yxyd.base.AppContext;
import com.yocard.yxyd.base.Constants;
import com.yocard.yxyd.http.model.request.CertRequest;
import com.yocard.yxyd.http.model.response.CommonBean;
import com.yocard.yxyd.others.GifSizeFilter;
import com.yocard.yxyd.others.Glide4Engine;
import com.yocard.yxyd.ui.activity.base.BaseActivity;
import com.yocard.yxyd.ui.contract.CertContract;
import com.yocard.yxyd.ui.dialog.CommonDialog;
import com.yocard.yxyd.ui.presenter.CertPresenter;
import com.yocard.yxyd.utils.util.ActivityUtils;
import com.yocard.yxyd.utils.util.ConvertUtils;
import com.yocard.yxyd.utils.util.IdcardValidator;
import com.yocard.yxyd.utils.util.StringUtils;
import com.yocard.yxyd.utils.util.ToastUtils;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.db.DBManager;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created on 2019/4/10.
 */
public class CertificationActivity extends BaseActivity<CertPresenter> implements CertContract.View {

    private static final int SELECT_POS_ID = 11;
    private static final int SELECT_POS_WORK_ID = 12;

    final String KEY_IC_URL = "shouchi";
    final String KEY_WORK_IC_URL = "gongpai";

    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.et_name)
    AppCompatEditText etName;
    @BindView(R.id.et_idnum)
    AppCompatEditText etIdnum;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.et_company_name)
    AppCompatEditText etCompanyName;
    @BindView(R.id.et_company_type)
    AppCompatEditText etCompanyType;
    @BindView(R.id.iv_id_front)
    ImageView ivIdFront;
    @BindView(R.id.iv_work_id)
    ImageView ivWorkId;
    @BindView(R.id.btn_submit_cert)
    Button btnSubmitCert;

    protected CommonDialog.Builder builder;
    String currentCityCode;
    boolean isSwichLocation;
    AMapLocationClient mLocationClient;
    protected boolean isReCert;
    protected String reCertId;
    Map<String, String> urlMap = new HashMap<>();

    @Override
    protected int getLayout() {
        return R.layout.act_certification;
    }

    @Override
    protected void initEventAndData() {
        initTitle();
        isSwichLocation = false;
        mPresenter.initLocation(mContext);
        builder = new CommonDialog.Builder(mContext).setTitle("确认退出认证")
                .setLeftText("确认退出")
                .setRightText("继续认证")
                .setLogo(R.mipmap.ic_wode_renzheng)
                .setListener(pos -> {
                    if (pos == CommonDialog.CLICK_POS_LEFT) {
                        super.onBackPressed();
                    }
                });
        etIdnum.addTextChangedListener(textWatcher);
        etName.addTextChangedListener(textWatcher);
        etCompanyName.addTextChangedListener(textWatcher);
        etCompanyType.addTextChangedListener(textWatcher);

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            isReCert = extras.getBoolean("isReCert", false);
            if (isReCert) {
                mPresenter.getRealName();
            }
        }
    }

    private void initTitle() {
        ImmersionBar.with(this).statusBarColor(R.color.white)
                .statusBarDarkFont(true).navigationBarColor(R.color.white).init();
        tvTitle.setText("信贷经理认证");
        tvRight.setText("提交");
        tvRight.setVisibility(View.GONE);
//        tvRight.setEnabled(false);
        btnSubmitCert.setEnabled(false);
    }

    @OnClick({R.id.iv_back, R.id.rl_city, R.id.iv_id_front, R.id.iv_work_id, R.id.btn_submit_cert})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.rl_city:
                switchCity();
                break;
//            case R.id.tv_right:
//                MobclickAgent.onEvent(mContext, "12", "click_cert_manager_next");
//                showLoadingDialog();
//                String name = etName.getText().toString().trim();
//                String idNum = etIdnum.getText().toString().trim();
//                mPresenter.postRealname(name, idNum, currentCityCode, reCertId);
//                break;
            case R.id.iv_id_front:
                selectImage(mContext, SELECT_POS_ID);
                break;
            case R.id.iv_work_id:
                selectImage(mContext, SELECT_POS_WORK_ID);
                break;
            case R.id.btn_submit_cert:
                String idNum = etIdnum.getText().toString().trim();
                if(!IdcardValidator.isValidatedAllIdcard(idNum)) {
                    ToastUtils.showShort(R.string.id_num_invalid);
                    return;
                }
                //防止短时间重复点击
                if (isFastDoubleClick()) return;

                MobclickAgent.onEvent(mContext, "12", "click_cert_manager_next");
                showLoadingDialog();
                String name = etName.getText().toString().trim();
                String companyName = etCompanyName.getText().toString().trim();
                String companyProperty = etCompanyType.getText().toString().trim();

                CertRequest request = new CertRequest();
                request.setName(name);
                request.setId_card_no(idNum);
                request.setCompany_name(companyName);
                request.setCompany_property(companyProperty);
                request.setId(reCertId);
                request.setCity_code(currentCityCode);
                request.setId_card_img(urlMap.get(KEY_IC_URL));
                request.setWork_card_img(urlMap.get(KEY_WORK_IC_URL));

//                mPresenter.postRealname(name, idNum, currentCityCode, reCertId);
                mPresenter.postRealname(request);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<Uri> uris = Matisse.obtainResult(data);
            List<String> paths = Matisse.obtainPathResult(data);

            showLoadingDialog();
            switch (requestCode) {
                case SELECT_POS_ID:
                    mPresenter.uploadImage(KEY_IC_URL, paths.get(0), ivIdFront, uris.get(0));
                    break;
                case SELECT_POS_WORK_ID:
                    mPresenter.uploadImage(KEY_WORK_IC_URL, paths.get(0), ivWorkId, uris.get(0));
                    break;
            }
        }
    }

    @Override
    public void uploadSuccess(String type, String picId, ImageView iv, Uri filePath) {
        Glide4Engine.getInstance().loadThumbnail(mContext, ConvertUtils.dp2px(120), null, iv, filePath);
        dismisDialog();
        urlMap.put(type, picId);
        caseStatus();

    }

    public void selectImage(Activity activity, int requestCode) {
        try {
            AndPermission.with(AppContext.getContext())
                    .runtime()
                    .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE, Permission.CAMERA)
                    .onGranted(permissions -> {
                        Matisse.from(activity)
                                .choose(MimeType.ofImage())
                                .theme(R.style.Matisse_Dracula)
                                .countable(false)
                                .capture(true) //是否提供拍照功能
                                .captureStrategy(new CaptureStrategy(true,mContext.getPackageName() + ".fileprovider"))//存储到哪里
                                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                                .maxSelectable(1)
                                .originalEnable(true)
                                .maxOriginalSize(10)
                                .imageEngine(Glide4Engine.getInstance())
                                .forResult(requestCode);
                    })
                    .onDenied(permissions -> {
                        ToastUtils.showLong("请授予APP相应权限");
                    })
                    .start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void switchCity() {
        isSwichLocation = true;
        mPresenter.switchCity(onPickListener, this);
    }

    OnPickListener onPickListener = new OnPickListener() {
        @Override
        public void onPick(int i, City city) {
            currentCityCode = city.getCode();
            tvCity.setText(city.getName());
            caseStatus();
        }

        @Override
        public void onLocate() {
            if (mLocationClient == null) {
                mPresenter.initLocation(CertificationActivity.this);
            } else {
                onLocationInit(mLocationClient);
            }
        }

        @Override
        public void onCancel() {

        }
    };

    @Override
    public void onBackPressed() {
        builder.show();
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }


    @Override
    public void onLocationInit(AMapLocationClient locationClient) {
        if (mLocationClient == null) {
            DBManager dbManager = new DBManager(getContext());
            mLocationClient = locationClient;
            mLocationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation location) {
                    String city = location.getCity();
                    List<City> cities = dbManager.searchCity(city);
                    if (cities != null && cities.size() > 0) {
                        City seachCity = cities.get(0);

                        if (isSwichLocation) {
                            CityPicker.from(CertificationActivity.this).locateComplete(new LocatedCity(seachCity.getName()
                                    , seachCity.getCode()), LocateState.SUCCESS);
                        } else {
                            tvCity.setText(seachCity.getName());
                            currentCityCode = seachCity.getCode();
                            caseStatus();
                        }
                    }
                }
            });
        }
        mLocationClient.startLocation();
    }

    @Override
    public void onPostSuccess() {
        dismisDialog();
        EventBus.getDefault().post(new CommonBean(Constants.CODE_REFRESH));
        Bundle bundle = new Bundle();
        bundle.putString("approval_status", Constants.AUTH_APPROVING);
        ActivityUtils.startActivity(bundle, CertResultActivity.class);
        ActivityUtils.finishActivity(this);
    }

    @Override
    public void onGetRealName(CommonBean bean) {
        etName.setText(bean.getName());
        etIdnum.setText(bean.getId_card_no());
        reCertId = bean.getId();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
        }
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            caseStatus();
        }
    };

    private void caseStatus() {
        String name = etName.getText().toString();
        String idNum = etIdnum.getText().toString();
        String companyName = etCompanyName.getText().toString();
        String companyType = etCompanyType.getText().toString();
        if (!StringUtils.isEmpty(currentCityCode) && !StringUtils.isEmpty(name) &&
                !StringUtils.isEmpty(idNum) && !TextUtils.isEmpty(companyName) && !TextUtils.isEmpty(companyType) &&
                urlMap.size() == 2) {
//            tvRight.setEnabled(true);
            btnSubmitCert.setEnabled(true);
        } else {
//            tvRight.setEnabled(false);
            btnSubmitCert.setEnabled(false);
        }
    }

}
